package com.ytrsoft.ui;

import cn.hutool.core.util.StrUtil;
import com.ytrsoft.entity.Params;
import com.ytrsoft.util.GenerateLyrics;
import com.ytrsoft.util.Message;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.util.List;

public class AppPane extends JPanel implements LeftPane.Submit, GenerateLyrics.Task {

    private boolean isRequest;
    private final RightPane rightPane;
    private final JProgressBar progressBar;

    public AppPane() {
        setLayout(new BorderLayout());

        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.setPreferredSize(new Dimension(0, 10));

        progressBar = new JProgressBar();
        progressBar.setStringPainted(false);
        progressBar.setVisible(false);
        topPanel.add(progressBar, BorderLayout.CENTER);

        add(topPanel, BorderLayout.NORTH);

        LeftPane leftPane = new LeftPane();
        leftPane.setBorder(new EmptyBorder(0, 10, 10, 10));
        leftPane.setOnSubmit(this);
        add(leftPane, BorderLayout.WEST);

        rightPane = new RightPane();
        rightPane.setBorder(new EmptyBorder(0, 10, 10, 10));
        add(rightPane, BorderLayout.CENTER);
    }

    @Override
    public void onSubmit(Params params) {
        if (isRequest) {
            return;
        }
        String input = params.getInput();
        if (StrUtil.isBlank(input)) {
            Message.warn("请输入关键歌词");
        } else {
            isRequest = true;
            setProgressBarVisible(true);
            GenerateLyrics generator = new GenerateLyrics(params);
            generator.setOnTask(this);
            generator.start();
        }
    }

    @Override
    public void onData(List<String> list) {
        rightPane.setLyricist(list);
    }

    @Override
    public void onDone() {
        isRequest = false;
        setProgressBarVisible(false);
    }

    @Override
    public void onError(String error) {
        setProgressBarVisible(false);
        Message.err(error);
    }

    private void setProgressBarVisible(boolean visible) {
        progressBar.setIndeterminate(visible);
        progressBar.setVisible(visible);
    }
}
